<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>会员分组</title>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/bootcdn/BootCDN/ajax/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/font-awesome.min93e3.css"/>
<link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/plugins/datapicker/bootstrap-datetimepicker.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/themes/default/style.min.css" rel="stylesheet">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/style.min.css"/>
<style type="text/css">
body{font-size: 14px;padding-top: 10px;}
.btn.btn-rounded{margin-bottom: 8px;}
.ruleForm{width: 100%;border-collapse: collapse;}
.ruleForm td{border: 1px dashed #ddd;padding: 4px;}
.ruleForm input.form-control{width: 160px;display: inline-block;}
.ruleForm select.form-control{width: 100px;display: inline-block;}
.ruleForm td:first-child>select.form-control{width: 60px;}
.ruleForm[tablename="标签属性"] td:first-child>select.form-control{width: 90px;}
.ruleForm td:last-child{width:50px;}
.ruleForm img{cursor: pointer;}
#ruleForm table.ruleForm{margin-bottom: 20px;}
.dropdown-menu>.active>a{background-color: #1ab394}
.dropdown-menu>.active>a:hover{background-color: #1ab394}
.ui-state-active,.ui-widget-content .ui-state-active{background-color: #1ab394;border-color: #1ab394;}
</style>
</head>
<body class="gray-bg">
<div class="container-fluid">
	<div class="row">
		<div class="col-sm-3">
	        <div class="ibox">
	            <div class="ibox-title" style="padding: 0;">
	            	<div style="display:inline-block;width:49%;line-height:44px;border-right: 1px solid #eee;text-align: center;">
	            		<shiro:hasPermission name="member_list_group:create_type">
		            		<a onclick="func_saveGroup1()">新建分类</a>
	            		</shiro:hasPermission>
	            	</div>
	            	<div style="display:inline-block;width:49%;text-align: center;">
	            		<shiro:hasPermission name="member_list_group:create_group">
		            		<a>新建分组</a>
	            		</shiro:hasPermission>
	            	</div>
	            </div>
	            <div class="ibox-content">
	            	<div class="row">
	            		<div class="input-group">
				            <input id="keyword" type="text" placeholder="输入名称搜索" class="form-control"> <span class="input-group-btn"> 
				            <button onclick="func_searchTree()" type="button" class="btn btn-primary">搜索</button> </span>
				        </div>
	            	</div>
	            	<div style="height:1px;border-top: 1px solid #eee;margin: 16px -20px;"></div>
	            	<div class="row">
	            		<div id="jsTree">
	            		
	            		</div>
	            	</div>
	            </div>
	        </div>
	    </div>
	    <div class="col-sm-5">
	        <div class="ibox ">
	            <div class="ibox-title">
	            	<table style="width: 100%;border-collapse:separate; border-spacing:0px 8px;">
	            		<tr>
	            			<td style="width: 60px;">分组名称</td>
	            			<td><input id="name2" placeholder="请输入分组名称" maxlength="20" class="form-control"> </td>
	            			<td style="width: 120px;">
<!-- 	            				<a onclick="func_showImportMemberDialog()">导入会员进行分组</a> -->
	            			</td>
	            		</tr>
	            		<tr>
	            			<td>所属分类</td>
	            			<td>
	            				<select id="fenlei" class="form-control"></select>
	            			</td>
	            			<shiro:hasPermission name="member_list_group:create_type">
	            			<td>&nbsp;&nbsp;<a onclick="func_saveGroup1()">新建分类</a></td>
	            			</shiro:hasPermission>
	            		</tr>
	            		<tr>
	            			<td>分组类型</td>
	            			<td>
	            				<select id="status" class="form-control">
	            					<option value="1">静态分组</option>
	            					<option value="2">动态分组</option>
	            				</select>
	            			</td>
	            			<td></td>
	            		</tr>
	            	</table>
	            </div>
	            <div id="ruleForm" class="ibox-content">
	            	<div id="save_btn" class="text-right" style="display: none;">
	            		<button onclick="func_saveGroup2()" class="btn btn-primary" type="button">生成分组</button>
	            		<button onclick="func_cleanAllRule()" class="btn btn-white" type="button" style="border-color: #18a689;">清空条件</button>
	            	</div>
	            </div>
	        </div>
	    </div>
	    <div class="col-sm-4 memberGroupRule">
			<div class="ibox">
	            <div class="ibox-title" style="padding: 0;min-height: 0;">
	            </div>
	            <div class="ibox-content" style="border-top: 0;">
	                <div class="panel-body">
	                    <div class="panel-group" id="accordion">
	                        <div class="panel panel-default">
	                            <div class="panel-heading">
	                                <h5 class="panel-title">
                                        <a data-toggle="collapse" data-parent="#accordion" href="tabs_panels.html#collapseOne">
                                        	基础属性</a>
                                    </h5>
	                            </div>
	                            <div id="collapseOne" class="panel-collapse collapse in">
	                                <div class="panel-body">
	                                	<a id="name" class="btn btn-default btn-rounded">姓名</a>
	                                	<a id="phone" class="btn btn-default btn-rounded">电话</a>
	                                	<a id="wechat" class="btn btn-default btn-rounded">微信</a>
	                                	<a id="gender" class="btn btn-default btn-rounded">性别</a>
	                                	<a id="birthday" class="btn btn-default btn-rounded">生日</a>
	                                	<a id="QQ" class="btn btn-default btn-rounded">QQ</a>
	                                	<a id="province" class="btn btn-default btn-rounded">省份</a>
	                                	<a id="email" class="btn btn-default btn-rounded">邮箱</a>
	                                	<a id="crm_member_level" class="btn btn-default btn-rounded">等级</a>
	                                	<a id="crm_score" class="btn btn-default btn-rounded">积分</a>
	                                	<a id="crm_balance" class="btn btn-default btn-rounded">储值</a>
	                                	<a id="store_name" class="btn btn-default btn-rounded">门店</a>
	                                	<a id="market_name" class="btn btn-default btn-rounded">销售</a>
										<a id="create_time" class="btn btn-default btn-rounded">注册时间</a>
	                                	<%--<a id="is_potential" class="btn btn-default btn-rounded">类型</a>--%>
	                                </div>
	                            </div>
	                        </div>
	                        <div class="panel panel-default">
	                            <div class="panel-heading">
	                                <h4 class="panel-title">
		                                <a data-toggle="collapse" data-parent="#accordion" href="tabs_panels.html#collapseTwo">
		                                	交易属性</a>
		                            </h4>
	                            </div>
	                            <div id="collapseTwo" class="panel-collapse collapse">
	                                <div class="panel-body">
										<a id="trade_time" class="btn btn-default btn-rounded">下单时间</a>
										<a id="trade_price" class="btn btn-default btn-rounded">下单金额</a>
										<a id="unit_price" class="btn btn-default btn-rounded">原价</a>
										<a id="discount_price" class="btn btn-default btn-rounded">折扣金额</a>
										<a id="goods_name" class="btn btn-default btn-rounded">商品名称</a>
	                                </div>
	                            </div>
	                        </div>
	                        <div class="panel panel-default">
	                            <div class="panel-heading">
	                                <h4 class="panel-title">
	                                    <a data-toggle="collapse" data-parent="#accordion" href="tabs_panels.html#collapseThree">
	                                    	RFM属性</a>
	                                </h4>
	                            </div>
	                            <div id="collapseThree" class="panel-collapse collapse">
	                                <div class="panel-body">
	                                	<!-- <a id="last_cost_time" class="btn btn-default btn-rounded">最后下单日期</a> -->
	                                	<a id="cost_count" class="btn btn-default btn-rounded">客户购买次数</a>
	                                	<a id="cost_total" class="btn btn-default btn-rounded">购买总金额</a>
	                                	<a id="goods_total" class="btn btn-default btn-rounded">购买商品件数</a>
	                                	<a id="average_cost" class="btn btn-default btn-rounded">平均购买价格</a>
	                                	<!-- <a id="first_cost_time" class="btn btn-default btn-rounded">首次下单日期</a> -->
	                                	<a id="first_cost" class="btn btn-default btn-rounded">首次购买金额</a>
	                                	<a id="last_cost" class="btn btn-default btn-rounded">最后一次购买金额</a>
	                                	<a id="average_goods_quantity" class="btn btn-default btn-rounded">平均购买件数</a>
	                                	<a id="max_cost" class="btn btn-default btn-rounded">最大单笔购买金额</a>
	                                	<a id="first_cost_num" class="btn btn-default btn-rounded">首次下单时间</a>
	                                	<a id="last_cost_num" class="btn btn-default btn-rounded">最后下单时间</a>
	                                </div>
	                            </div>
	                        </div>
	                        <div class="panel panel-default">
	                            <div class="panel-heading">
	                                <h4 class="panel-title">
	                                    <a data-toggle="collapse" data-parent="#accordion" href="tabs_panels.html#collapseFour">
	                                    	标签属性</a>
	                                </h4>
	                            </div>
	                            <div id="collapseFour" class="panel-collapse collapse">
	                                <div class="panel-body">
	                                	建设中
<!-- 	                                	<a id="tag_eat_hot" class="btn btn-default btn-rounded">爱吃辣</a> -->
	                                </div>
	                            </div>
	                        </div>
	                    </div>
	                </div>
	            </div>
	        </div>
	    </div>
	</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/bootcdn/BootCDN/ajax/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/jstree.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/artDialog/7.0.0/dialog-plus.js"></script>
<script type="text/javascript" src="<%=path%>/hplus/js/plugins/datapicker/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="<%=path%>/hplus/js/plugins/datapicker/bootstrap-datetimepicker.zh-CN.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/spin.js/2.3.2/spin.min.js"></script>
<script type="text/javascript" src="<%=path%>/js/printShade.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript"  src="<%=path%>/js/system/province-city-area-data.js"></script>
<script type="text/javascript">
var path = "<%=path%>";
document.write("<script src='"+path+"/js/memberGroupRule.js?r="+Math.random()+"'><\/script>");

var importMemberDialog = null;
var provinceArr = null;		//省份数组

$(function(){
	//为右侧标签打上规则
	$.each(memberGroupRule,function(key,val){
		$("a[id='"+key+"']").attr("rule",val);
	});
	
	init();

	//右侧标签点击
	$(".memberGroupRule a.btn.btn-rounded").click(function(){
		var ruleHead = $.trim($(this).parents(".panel").find(".panel-title").text());
		var ruleText = $(this).text();
		var ruleSymbol = $(this).attr("rule");
		var ruleName = $(this).attr("id");
		
		var random = parseInt(Math.random()*10000000) + '';
		
		if($(this).hasClass("btn-default")){	//判断按钮状态，灰色需要添加属性，
			$(this).removeClass("btn-default").addClass("btn-primary");
			
			var countTable = 0;		//标识符，如果已存在table，后续添加属性，只能是追加
			$("#ruleForm>table").each(function(i,d){
				if($(d).attr("tableName") == ruleHead){
					countTable++;
					return false;
				}
			});

            var id = 'id="'+ruleName+'"';
			if(countTable == 0){	//不存在table，直接添加属性
				if(ruleHead != "标签属性"){
					var table = "<table tableName='"+ruleHead+"' class='ruleForm'><caption>"+ruleHead+"</caption><tr trName='"+ruleName+"'><td>"+ruleText+"</td><td>";
					
					var select = "<select onchange='selectChange(this, this[selectedIndex].value)' class='form-control'>";
					
					select += func_option(ruleSymbol,ruleName);
					
					select += "</select>";
					
					table += select;
					
					var dateClass = 'class="form-control '+ random +'"';
					if($.inArray(ruleName,timeComponent)>=0){
						dateClass = 'class="form-control datetime" readonly ';
					}
					var input_text = "<input "+dateClass+" "+id+">";
					if(ruleName == "is_potential"){	//1：会员，2：潜客。
						input_text = "<select class='form-control'><option value='2'>潜客</option><option value='1'>会员</option></select>";
						table += input_text;
						table += "</td><td><img class='"+ random +"' trName='"+ruleName+"' src='"+path+"/images/delete_16.png'></td></tr></table>";
					}else{
						table += input_text;
						table += "</td><td><img ruleSymbol='"+ruleSymbol+"' src='"+path+"/images/add_16.png'>&nbsp;&nbsp;<img trName='"+ruleName+"' src='"+path+"/images/delete_16.png'></td></tr></table>";
					}
					$("#ruleForm").append(table);
				}else if(ruleHead == "标签属性"){
					var table = "<table tableName='"+ruleHead+"' class='ruleForm'><caption>"+ruleHead+"</caption><tr trName='"+ruleName+"'><td style='width:100px;'>";
					table += '<select class="form-control"><option value="in">包含</option><option value="not in">不包含</option></select>';
					table += "</td><td>";
					table += ruleText;
					table += "</td><td><img trName='"+ruleName+"' src='"+path+"/images/delete_16.png'></td></tr></table>";
					$("#ruleForm").append(table);
				}
			}else{		//已存在table，后续属性需要添加
				var tr = "<tr trName='"+ruleName+"'>";
				tr += "<td>"+ruleText+"</td>";
				tr += "<td><select onchange='selectChange(this, this[selectedIndex].value)' class='form-control'>";
				
				tr += func_option(ruleSymbol,ruleName);
				
				var dateClass = 'class="form-control '+ random +'"';
				if($.inArray(ruleName,timeComponent)>=0){
					dateClass = 'class="form-control datetime" readonly ';
				}
				if(ruleName == "is_potential"){	//1：会员，2：潜客。
					tr += "</select><select class='form-control'><option value='2'>潜客</option><option value='1'>会员</option></select></td>";
					tr += "<td><img class='"+random+"' trName='"+ruleName+"' src='"+path+"/images/delete_16.png'></td>";
					tr += "</tr>";
				}else{
					tr += "</select><input "+dateClass+" "+id+"></td>";
					tr += "<td><img class='"+random+"' ruleSymbol='"+ruleSymbol+"' src='"+path+"/images/add_16.png'>&nbsp;&nbsp;<img trName='"+ruleName+"' src='"+path+"/images/delete_16.png'></td>";
					tr += "</tr>";
				}
				$("#ruleForm>table[tableName='"+ruleHead+"']").append(tr);
			}
			if(ruleName == "first_cost_num"){
				first_order_num_input(random);
			}
			if(ruleName == "last_cost_num"){
	        	last_order_num_input(random);
			}
			$(".datetime").datetimepicker({language:"zh-CN",format: 'yyyy-mm-dd',autoclose: true,minView:2});
            $(".datetime").datetimepicker("setEndDate",new Date());
		}else if($(this).hasClass("btn-primary")){		//需要移除对应属性
			$(this).removeClass("btn-primary").addClass("btn-default");
			$("#ruleForm>table[tableName='"+ruleHead+"'] tr[trName='"+ruleName+"']").remove();
			if($("#ruleForm>table[tableName='"+ruleHead+"'] tr").length == 0){
				$("#ruleForm>table[tableName='"+ruleHead+"']").remove();
			}
			
			if($("#ruleForm>table").length == 0){
				$("#ruleForm>#save_btn").hide();
			}
		}
		
		if($("#ruleForm>table").length > 0){	//显示最下面 生成分组，清空条件 2个按钮
			$("#ruleForm>#save_btn").insertAfter("#ruleForm>table:last");
			$("#ruleForm>#save_btn").show();
		}
	});
	
	//删除按钮点击事件，如果父节点删除，则需要删除全部属性，小节点删除，只需删除当前行。
	$(document).on("click","#ruleForm>table img[src$='/images/delete_16.png']",function(){
		var tr = $(this).parents("tr");
		var table = tr.parents("table");
		var trName = tr.attr("trName")
		if(trName == $(this).attr("trName")){	//根节点删除
			table.find("tr[trName='"+trName+"']").remove();
			$("a[id='"+trName+"']").removeClass("btn-primary").addClass("btn-default");
			if(table.find("tr").length == 0){
				table.remove();
			}
			if($("#ruleForm>table").length == 0){
				$("#ruleForm>#save_btn").hide();
			}
		}else{	//小节点删除
			tr.remove();
		}
		func_qieHuo();
	});

	//添加按钮点击事件
	$(document).on("click","#ruleForm>table img[src$='/images/add_16.png']",function(){
		// console.log(event, this.parentNode.parentNode.children[1]);
		// var targetTd = this.parentNode.parentNode; //要加“天”字的那个td
		
		var random = parseInt(Math.random()*10000000) + '';
		
		var tr = $(this).parents("tr");
		var table = tr.parents("table");
		var trName = tr.attr("trName")
		var ruleSymbol = $(this).attr("ruleSymbol");
		
		var tr = "<tr trName='"+trName+"'>";
		tr += "<td><select class='form-control'><option value='&&'>且</option><option value='||'>或</option></select></td>";
		tr += "<td><select onchange='selectChange(this, this[selectedIndex].value);' class='form-control'>";
		
		tr += func_option(ruleSymbol,trName);
		
		var dateClass = 'class="form-control '+random+'"';
        var id = 'id="'+trName+'"';
		if($.inArray(trName,timeComponent)>=0){
			dateClass = 'class="form-control datetime" readonly ';
		}
		tr += "</select><input "+dateClass+" "+id+"></td>";
		tr += "<td><img class='"+random+"' ruleSymbol='"+ruleSymbol+"' src='"+path+"/images/add_16.png'>&nbsp;&nbsp;<img src='"+path+"/images/delete_16.png'></td>";
		tr += "</tr>";
		
		table.find("tr[trName='"+trName+"']:last").after(tr);
		$(".datetime").datetimepicker({language:"zh-CN",format: 'yyyy-mm-dd',autoclose: true,minView:2});
        $(".datetime").datetimepicker("setEndDate",new Date());
		func_qieHuo();
		if(trName == "first_cost_num"){
			first_order_num_input(random);
		}
		if(trName == "last_cost_num"){
        	last_order_num_input(random);
		}
	});

    //rfm下单时间输入框控制
    function first_order_num_input(className){
		var input = $('.' + className)[0];

		var span = $(input).nextSibling;
		if (!span) {
			input.after('天');
		}
        $(input).attr("style","width:148px");
        $("input[id='first_cost_num']").on("keyup",function(){
            $("input[id='first_cost_num']").attr("maxlength",4);
            if(this.value.substr(0, 1)=="0"){
                this.value='';
            }else{
                this.value=this.value.replace(/\D/g,'');
            }
        });
    }
    
    function last_order_num_input(className){
    	var input = $('.' + className)[0];

		var span = $(input).nextSibling;
		if (!span) {
			input.after('天');
		}
        $(input).attr("style","width:148px");
       $("input[id='last_cost_num']").on("keyup",function(){
           $("input[id='last_cost_num']").attr("maxlength",4);
           if(this.value.substr(0, 1)=="0"){
               this.value='';
           }else{
               this.value=this.value.replace(/\D/g,'');
           }
       });
   }

	//商品名称匹配
	$(document).on("click","tr[trName='goods_name']",function(){
		$(this).find("td:eq(1)>:text").autocomplete({
			source: function( request, response ) {
				$.post(path+"/memberGroup/ajaxListMedicineNameLikeName",{name:request.term},function(data){
					if(data.code == "0"){
						response(data.data);
					}
				},"json");
			}
		});
	});
	
	
	//省份自动匹配
	$(document).on("click","tr[trName='province']",function(){
		$(this).find("td:eq(1)>:text").autocomplete({
			source: provinceArr
		});
	});
	
	//且或关系统一处理
	$(document).on("change","select",function(){
		var index = $(this).parent().index();
		if(index == 0){
			func_qieHuo();
		}
	});
});

//select 改变
function selectChange(obj, value){
    var inputDom = obj.nextSibling;
    if (value == 'null'){
        inputDom.setAttribute("disabled", "block");
    }else{
        inputDom.removeAttribute("disabled");
	}
}

function init(){
	$.post(path+"/memberGroup/ajaxGroupTree",function(data){
		if(data.status != "200"){
			alert("远程请求出错");
			return ;
		}
		if($.jstree.reference('#jsTree') != null){
			$.jstree.reference('#jsTree').destroy();
		}
		var tree = "";
		var option = "";
		tree += "<ul>";
		$.each(data.data,function(i,d){
			var text1 = "";
			var text2 = d.text;
			if(d.text.length > 5){
				text1 = text2;
				text2 = text1.substr(0,4)+"...";
			}
			tree += "<li id='"+d.id+"' data-jstree='{\"type\":\"top\"}' title='"+text1+"'>";
			tree += text2;
			tree += "<ul>";
			
			option += "<option value='"+d.id+"'>"+d.text+"</option>"
			$.each(d.children,function(i2,d2){
				var text1 = "";
				var text2 = d2.text;
				if(d2.text.length > 5){
					text1 = text2;
					text2 = text1.substr(0,4)+"...";
				}
				tree += "<li id='"+d2.id+"' title='"+text1+"'>";
				tree += text2;
			});
			tree += "</ul>";
			tree += "</li>";
		});
		tree += "</ul>";
		$("#jsTree").html(tree);
		$("#fenlei").html(option);
		
		$("#jsTree").jstree({
			core: {
		    	themes: {
					dots: false
				},
				"check_callback" : true
			},
			"types" : {
			    "default" : {
			      	"icon" : path+"/images/Artboard2.png"
			    },
			    "top" : {
			      	"icon" : path+"/images/Artboard.png"
			    }
			},
			"plugins" : [ "types","search","contextmenu" ],
			contextmenu: {
				items: {
					<shiro:hasPermission name="member_list_group:update">
		            "rename": {
		            	"label": "修改",
						"action": function (obj) {
							var inst = jQuery.jstree.reference(obj.reference);
			            	var clickedNode = inst.get_node(obj.reference);
			            	inst.edit(obj.reference,clickedNode.val,function(new_node){
			            		var groupId = new_node.id;
			            		var name = new_node.text;
			            		$.post(path+"/memberGroup/ajaxRename",{id:groupId,name:name});
			            	})
		            	}
		            },
		            </shiro:hasPermission>
		            <shiro:hasPermission name="member_list_group:delete">
		            "remove": {
		            	"label": "删除",
		            	"action": function (obj) {
			            	var inst = jQuery.jstree.reference(obj.reference);
			            	var clickedNode = inst.get_node(obj.reference);
			            	if(clickedNode.children.length > 0){
			            		if(!confirm("您好，删除分类后，分类下属的所有分组将全部删除，是否确认删除？点击“确定”进行删除，点击取消返回页面。")){
			            			return ;
			            		}
			            	}else if(clickedNode.parents.length==2){
			            		if(!confirm("您好，删除分组后，分组内会员将会全部删除，是否确认删除？点击“确定”进行删除，点击取消返回页面。")){
			            			return ;
			            		}
			            	}
			            	var temp_groupId =  clickedNode.id;
			            	var isContains = false;
			            	$.each(clickedNode.children,function(i,d){
			            		temp_groupId += "," + d;
			            	});
			            	$.post(path+"/memberGroup/ajaxDelGroupAll",{groupId:temp_groupId},function(data){
			            		if(data.status == "200"){
					            	inst.delete_node(obj.reference);
			        				if(isContains){
				        				location.href = path+"/view/member/member/group";
			        				}
			        			}
			        		},"json");
		            	}
		            }
		            </shiro:hasPermission>
				}
			}
		}).on("click.jstree",function(e){
			var nodeId = $.jstree.reference('#jsTree').get_selected()[0];
			var node = $.jstree.reference('#jsTree').get_node(nodeId);
			if(node){
				if(node.children.length==0 && node.parents.length==2){
					var groupId = node.id;
					location.href = path+"/view/member/member/groupList?groupId="+groupId;
				}
			}
		});
	},"json");
	
	func_initProvinceArr();
}

//清空所有条件
function func_cleanAllRule(){
	$(".memberGroupRule a.btn.btn-rounded").removeClass("btn-primary").addClass("btn-default");
	$("#ruleForm>table").remove();
	$("#ruleForm>#save_btn").hide();
}

function func_searchTree(){
	$("#jsTree").jstree(true).search($.trim($("#keyword").val()));
}

//保存分类
function func_saveGroup1(){
	var d = dialog({
		title: '新建分类',
		content: '<input id="name3" placeholder="请输入分类名称"/>',
		okValue: "保存",
		ok: function () {
			var name = $('#name3').val();
			name = $.trim(name);
			if(name == ""){
				alert("请输入分类名称");
				return false;
			}
			var json = {};
			json.name = name;
			json.type = 1;
			
			$.post(path+"/memberGroup/ajaxGroupSave",json,function(data){
				if(data.status == "200"){
	    			init();
	    		}else{
	    			alert("保存失败");
	    		}
			},"json");
			this.close();
			this.remove();
        }
	});
	d.show();
    if($('.ui-dialog')[1]){
        d.remove();
    }
}

//保存分组
function func_saveGroup2(){
	var json = {};
	if($("#ruleForm>table").length == 0){
		return ;
	}
	
	var type = 2;
	var name = $.trim($("#name2").val());
	var parent_id = $("#fenlei").val();
// 	var status = $("#status").val();
	var status = $("select[id='status']").val();
	
	if(name == ""){
		alert("分组名称不能为空");
		return ;
	}
	if(parent_id == null){
		alert("请先创建分类");
		return ;
	}
	
	var isProvince = true;
	$.each($("tr[trName='province']"),function(i,d){
		var provinceCode = getProvinceCode($.trim($(d).find("td:eq(1)>:text").val()));
		if(provinceCode == ""){
			isProvince = false;
			return false;
	 	}
	});
	
	if(!isProvince){
		alert("请根据提示，输入正确的省份");
		return ;
	}
	
	
	json.type = type;
	json.name = name;
	json.parentId = parent_id;
	json.status = status;
	
	$("#ruleForm>table").each(function(i,d){
		var jsonArr = [];
		if($(d).attr("tableName") == "基础属性"){
			func_getTr(d,jsonArr);
			console.log("jsonArr-->"+jsonArr);
			json.baseAttr = JSON.stringify(jsonArr);
		}else if($(d).attr("tableName") == "交易属性"){
			func_getTr(d,jsonArr);
			json.tradeAttr = JSON.stringify(jsonArr);
		}else if($(d).attr("tableName") == "RFM属性"){
			func_getTr(d,jsonArr);
			json.rfmAttr = JSON.stringify(jsonArr);
		}else if($(d).attr("tableName") == "标签属性"){
			json.tagAttr = JSON.stringify(jsonArr);
		}
	});
	
	printShadeShow();
	
	$.post(path+"/memberGroup/ajaxGroupSave",json,function(data){
        printShadeHide();
        if(data.status == "200"){
			var groupId = data.data;
			setTimeout(
                location.href = path+"/view/member/member/groupList?groupId="+groupId
            , 2000)
		}else{
			alert("保存失败");
		}
	},"json");
	
// 	$.ajax({
// 		contentType: 'text/plain;charset=utf-8',
// 		dataType: 'json',
//     	type: 'POST',
//     	url: path+"/scan/memberGroup/saveGroup",
//     	data: JSON.stringify(json),
//     	success: function(data){
//     		if(data.msg_code == 1){
//     			printShadeHide();
//     			var groupId = data.data;
//     			location.href = path+"/view/member/member/groupList?groupId="+groupId;
//     		}else if(data.msg_code == 1){
//     			alert("保存失败");
//     		}
//     	}
// 	});
}

//导入会员进行分组
function func_showImportMemberDialog() {
	alert("请前往平台进行操作");
	return ;
	
	if(!confirm("请注意！\n导入会员进行分组为静态分组，不可更改！\n是否继续")){
		return ;
	}
	
	var name = $.trim($("#name2").val());
	var parentId = $("#fenlei").val();
	if(name == ""){
		alert("请输入分组名称");
		return ;
	}
	
    importMemberDialog = dialog({
        width: 400,
        height: 300,
        title: '导入会员',
        url: encodeURI(path + "/view/member/member/importMember?isGroup=true&name="+encodeURIComponent(name)+"&parentId="+parentId)
    });
    
    importMemberDialog.showModal();
}

//获取各个table的tr属性
function func_getTr(d,jsonArr){
	$(d).find("tr").each(function(i2,d2){
		var trName = $(d2).attr("trName");
		if($(d2).find("td:first>select").length == 0){	//一组条件的第一行
			var tempJson = {};
			var trRule = "";
			var td2 = $(d2).find("td:eq(1)>select").val();	//第二列td，是一些 =,!= 符号
			var temp = "";	//判断locate=0 或者是 locate>0，用于处理包含的条件
			if(td2 == "in"){	//包含
				td2 = "locate(";
				temp = ")>0";
			}else if(td2 == "notIn"){	//不包含
				td2 = "locate(";
				temp = ")=0";
			}else{
				trRule += trName;
			}
			trRule += td2;
			if(trName == "is_potential"){		//会员状态
				trRule += $(d2).find("td:eq(1)>select:last").val();
			}else if(trName == "gender"){		//性别
				var gender = $.trim($(d2).find("td:eq(1)>:text").val());
				if(gender=='男' || gender == 'm'){
					gender = 'm';
				}else if(gender=='女' || gender == 'f'){
					gender = 'f';
				}
				trRule += "'"+gender+"'";
			}else{		
				if($.inArray(trName,x100Val)>=0){	//金额相关的值，需要 x100
					trRule += "'"+$.trim($(d2).find("td:eq(1)>:text").val())+"00'";
				}else if(temp != ""){		//包含或者不包含的条件 拼接。
					trRule += "'"+$.trim($(d2).find("td:eq(1)>:text").val())+"',"+trName+temp;
				}else{
					if(trRule=="province="){
						var provinceCode = getProvinceCode($.trim($(d2).find("td:eq(1)>:text").val()));
						trRule += "'"+provinceCode+"'";
					}else{
						trRule += "'"+$.trim($(d2).find("td:eq(1)>:text").val())+"'";
					}
				}
			}
			
			tempJson.key = trName;
			tempJson.value = trRule;
			jsonArr.push(tempJson);
		}else{
			var trRule = " " + $(d2).find("td:first>select").val() + " ";
			var td2 = $(d2).find("td:eq(1)>select").val();	//第二列td，是一些 =,!= 符号
			var temp = "";	//判断locate=0 或者是 locate>0，用于处理包含的条件
			if(td2 == "in"){
				td2 = "locate(";
				temp = ")>0";
			}else if(td2 == "notIn"){
				td2 = "locate(";
				temp = ")=0";
			}else{
				trRule += trName;
			}
			trRule += td2;
			
			if(trName == "gender"){
				var gender = $.trim($(d2).find("td:eq(1)>:text").val());
				if(gender=='男' || gender == 'm'){
					gender = 'm';
				}else if(gender=='女' || gender == 'f'){
					gender = 'f';
				}
				trRule += "'"+gender+"'";
			}else{
				if($.inArray(trName,x100Val)>=0){
					trRule += "'"+$(d2).find("td:eq(1)>:text").val()+"00'";
				}else if(temp != ""){
					trRule += "'"+$.trim($(d2).find("td:eq(1)>:text").val())+"',"+trName+temp;
				}else{
					trRule += "'"+$(d2).find("td:eq(1)>:text").val()+"'";
				}
			}
			jsonArr[jsonArr.length-1].value = jsonArr[jsonArr.length-1].value + trRule;
		}
	});
}

//用于且或的状态，一个条件中，且或只有一种。
function func_qieHuo(){
	for(var i=0; i<$("tr[trName]").size(); i++){
		var trName = $("tr[trName]").eq(i).attr("trName");
		var thisTrNameSize = $("tr[trName='"+trName+"']").size();
		i += thisTrNameSize;
		
		var value = "";
		$("tr[trName='"+trName+"']").each(function(i,d){
			if(i == 0){
			}else if(i == 1){
				value = $(d).find("td:eq(0)>select").val();
				$(d).find("td:eq(0)>select").attr("disabled",false);
			}else{
				$(d).find("td:eq(0)>select>option[value='"+value+"']").attr("selected",true).siblings().removeAttr("selected");
				$(d).find("td:eq(0)>select").attr("disabled",true);
			}
		});
	}
}

//这个用于大于、小于、早于、晚于的处理
function func_option(ruleSymbol,ruleName){
	var listOption = "";
	
	$.each(ruleSymbol.split(","),function(i,d){
		var symbolName = "";
		if(d == "<"){
			if($.inArray(ruleName,timeComponent)>=0){
				symbolName = "早于";
			}else{
				symbolName = "小于";
			}
		}else if(d == "null"){
            symbolName = "等于［空］";
        }else if(d == "="){
			symbolName = "等于";
		}else if(d == "<="){
			if($.inArray(ruleName,timeComponent)>=0){
				symbolName = "早于等于";
			}else{
				symbolName = "小于等于";
			}
		}else if(d == ">"){
			if($.inArray(ruleName,timeComponent)>=0){
				symbolName = "晚于";
			}else{
				symbolName = "大于";
			}
		}else if(d == ">="){
			if($.inArray(ruleName,timeComponent)>=0){
				symbolName = "晚于等于";
			}else{
				symbolName = "大于等于";
			}
		}else if(d == "!="){
			symbolName = "不等于";
		}else if(d == "in"){
			symbolName = "包含";
		}else if(d == "notIn"){
			symbolName = "不包含";
		}
		listOption += "<option value='"+d+"'>"+symbolName+"</option>";
	});
	
	return listOption;
}

function func_initProvinceArr(){
	if(provinceArr == null){
		provinceArr = [];
		$.each(pcadata[100000],function(k,v){
	// 		{value:d.name,label:d.name,activityId:d.id}
			var temp = {};
			temp.value = v,
			temp.label = v;
			provinceArr.push(temp);
		});
	}
}

function getProvinceCode(provinceName){
	var provinceCode="";
	$.each(pcadata[100000],function(k,v){
		if(provinceName==v){
			provinceCode=k;
			return false;
		}
	});
	return provinceCode;
}
</script>
</html>